import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'cached_image_widget.dart';
import 'logger.dart';

/// 缓存管理工具类
/// 提供缓存大小查询、清除缓存等功能
class CacheManagerUtil {
  /// 获取缓存目录大小（字节）
  static Future<int> getCacheSize() async {
    try {
      int totalSize = 0;

      // 获取临时目录
      final tempDir = await getTemporaryDirectory();
      totalSize += await _getDirectorySize(tempDir);

      // 获取应用支持目录（用于存放缓存）
      final supportDir = await getApplicationSupportDirectory();
      totalSize += await _getDirectorySize(supportDir);

      Logger.d('CACHE_MANAGER', '缓存总大小: ${_formatSize(totalSize)}');
      return totalSize;
    } catch (e) {
      Logger.e('CACHE_MANAGER', '获取缓存大小失败: $e');
      return 0;
    }
  }

  /// 获取格式化的缓存大小字符串
  static Future<String> getFormattedCacheSize() async {
    final size = await getCacheSize();
    return _formatSize(size);
  }

  /// 清除所有缓存
  static Future<bool> clearAllCache() async {
    try {
      Logger.d('CACHE_MANAGER', '开始清除所有缓存...');

      // 清除图片缓存
      await AppCacheManager.clearCache();

      // 清除临时目录
      final tempDir = await getTemporaryDirectory();
      await _clearDirectory(tempDir);

      // 清除应用支持目录
      final supportDir = await getApplicationSupportDirectory();
      await _clearDirectory(supportDir);

      // 清除热门动态数据缓存
      await _clearHotPostsCache();

      Logger.d('CACHE_MANAGER', '所有缓存已清除');
      return true;
    } catch (e) {
      Logger.e('CACHE_MANAGER', '清除缓存失败: $e');
      return false;
    }
  }

  /// 仅清除图片缓存
  static Future<bool> clearImageCache() async {
    try {
      await AppCacheManager.clearCache();
      Logger.d('CACHE_MANAGER', '图片缓存已清除');
      return true;
    } catch (e) {
      Logger.e('CACHE_MANAGER', '清除图片缓存失败: $e');
      return false;
    }
  }

  /// 清除热门动态数据缓存
  static Future<void> _clearHotPostsCache() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final keys = prefs.getKeys();
      final hotPostsKeys =
          keys.where((key) => key.startsWith('hot_posts_cache_')).toList();

      for (final key in hotPostsKeys) {
        await prefs.remove(key);
      }

      Logger.d('CACHE_MANAGER', '热门动态缓存已清除，共 ${hotPostsKeys.length} 条');
    } catch (e) {
      Logger.e('CACHE_MANAGER', '清除热门动态缓存失败: $e');
    }
  }

  /// 获取目录大小
  static Future<int> _getDirectorySize(Directory dir) async {
    int size = 0;
    try {
      if (await dir.exists()) {
        await for (final entity in dir.list(recursive: true)) {
          if (entity is File) {
            size += await entity.length();
          }
        }
      }
    } catch (e) {
      // 忽略权限错误等
    }
    return size;
  }

  /// 清除目录内容（保留目录本身）
  static Future<void> _clearDirectory(Directory dir) async {
    try {
      if (await dir.exists()) {
        await for (final entity in dir.list()) {
          try {
            if (entity is File) {
              await entity.delete();
            } else if (entity is Directory) {
              await entity.delete(recursive: true);
            }
          } catch (e) {
            // 忽略单个文件删除失败
          }
        }
      }
    } catch (e) {
      Logger.e('CACHE_MANAGER', '清除目录失败: ${dir.path}, $e');
    }
  }

  /// 格式化文件大小
  static String _formatSize(int bytes) {
    if (bytes < 1024) {
      return '$bytes B';
    } else if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(2)} KB';
    } else if (bytes < 1024 * 1024 * 1024) {
      return '${(bytes / (1024 * 1024)).toStringAsFixed(2)} MB';
    } else {
      return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(2)} GB';
    }
  }

  /// 显示清除缓存确认对话框
  static Future<void> showClearCacheDialog(BuildContext context) async {
    final cacheSize = await getFormattedCacheSize();

    if (!context.mounted) return;

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('清除缓存'),
        content: Text('当前缓存大小: $cacheSize\n\n清除缓存后，图片和数据需要重新加载，确定要清除吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.pop(context);
              // 显示加载指示器
              showDialog(
                context: context,
                barrierDismissible: false,
                builder: (context) => const Center(
                  child: CircularProgressIndicator(),
                ),
              );

              final success = await clearAllCache();

              if (context.mounted) {
                Navigator.pop(context); // 关闭加载指示器
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Text(success ? '缓存已清除' : '清除缓存失败'),
                    backgroundColor: success ? Colors.green : Colors.red,
                  ),
                );
              }
            },
            child: const Text('确定', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }
}

/// 缓存设置页面组件
/// 可以嵌入到设置页面中使用
class CacheSettingsWidget extends StatefulWidget {
  const CacheSettingsWidget({super.key});

  @override
  State<CacheSettingsWidget> createState() => _CacheSettingsWidgetState();
}

class _CacheSettingsWidgetState extends State<CacheSettingsWidget> {
  String _cacheSize = '计算中...';
  bool _isClearing = false;

  @override
  void initState() {
    super.initState();
    _loadCacheSize();
  }

  Future<void> _loadCacheSize() async {
    final size = await CacheManagerUtil.getFormattedCacheSize();
    if (mounted) {
      setState(() {
        _cacheSize = size;
      });
    }
  }

  Future<void> _clearCache() async {
    setState(() {
      _isClearing = true;
    });

    final success = await CacheManagerUtil.clearAllCache();

    if (mounted) {
      setState(() {
        _isClearing = false;
        _cacheSize = '0 B';
      });

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(success ? '缓存已清除' : '清除缓存失败'),
          backgroundColor: success ? Colors.green : Colors.red,
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: const Icon(Icons.cleaning_services),
      title: const Text('清除缓存'),
      subtitle: Text('当前缓存: $_cacheSize'),
      trailing: _isClearing
          ? const SizedBox(
              width: 24,
              height: 24,
              child: CircularProgressIndicator(strokeWidth: 2),
            )
          : const Icon(Icons.chevron_right),
      onTap: _isClearing
          ? null
          : () async {
              final confirm = await showDialog<bool>(
                context: context,
                builder: (context) => AlertDialog(
                  title: const Text('清除缓存'),
                  content: Text(
                      '当前缓存大小: $_cacheSize\n\n清除缓存后，图片和数据需要重新加载，确定要清除吗？'),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.pop(context, false),
                      child: const Text('取消'),
                    ),
                    TextButton(
                      onPressed: () => Navigator.pop(context, true),
                      child:
                          const Text('确定', style: TextStyle(color: Colors.red)),
                    ),
                  ],
                ),
              );

              if (confirm == true) {
                await _clearCache();
              }
            },
    );
  }
}

